package cn.myzqu.sign.common.miniprogram.utils;


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * 网络请求工具类
 * @Author: 的川
 * @Date: 2018/5/10.
 */
@Slf4j 
public class HttpRequestUtil {


    /**
     * post请求
     * @param url
     * @param json
     * @return
     */
    public static JSONObject doPost(String url, JSONObject json){
        return doPost(url,json.toString());
    }

    /**
     * post请求
     * @param url
     * @param json
     * @return
     */
    public static JSONObject doPost(String url,String json){
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        JSONObject response = null;
        try {
            StringEntity s = new StringEntity(json, Charset.forName("utf-8"));
            s.setContentEncoding("UTF-8");
            //发送json数据需要设置contentType
            s.setContentType("application/json");
            post.setEntity(s);
            CloseableHttpResponse res = httpclient.execute(post);
            if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                // 返回json格式：
                String result = EntityUtils.toString(res.getEntity());
                response = JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return response;
    }



    /**
     * 
     * @param httpUrl
     * @param json
     * @return
     * @throws Exception
     */
    public static InputStream post(String httpUrl, String json)
            throws Exception {
        URL url = new URL(httpUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.connect();
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        out.append(json);
        out.flush();
        out.close();
        int code = connection.getResponseCode();
        InputStream is = null;
        if (code == 200) {
            is = connection.getInputStream();
        } else {
            is = connection.getErrorStream();
        }
        return is;
    }

    /**
     * GET请求
     * @param httpUrl
     * @param params
     * @return
     * @throws IOException
     */
    public static String get(String httpUrl, Map<String, Object> params)  {
        StringBuffer resultBuffer = null;
        StringBuffer paramsBuffer = new StringBuffer();
        //map转换为string
        if (params != null && params.size() > 0) {
            for (Map.Entry<String, Object> e : params.entrySet()) {
                paramsBuffer.append(e.getKey());
                paramsBuffer.append("=");
                paramsBuffer.append(e.getValue());
                paramsBuffer.append("&");
            }
        }
        HttpURLConnection con = null;
        OutputStreamWriter osw = null;
        BufferedReader br = null;
        try {
            URL url = new URL(httpUrl);
            con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            if (paramsBuffer != null && paramsBuffer.length() > 0) {
                osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
                osw.write(paramsBuffer.substring(0, paramsBuffer.length() - 1));
                osw.flush();
            }
            resultBuffer = new StringBuffer();
            int contentLength = Integer.parseInt(con.getHeaderField("Content-Length"));

            if (contentLength > 0) {
                br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
                String temp;
                while ((temp = br.readLine()) != null) {
                    resultBuffer.append(temp);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //关闭连接
            if(br!=null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(osw!=null) {
                try {
                    osw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(con!=null) {
                con.disconnect();
            }
        }
        return resultBuffer.toString();

    }
}
